package com.hsj.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.AttributeKey;

public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup();
        
        AttributeKey<String> abk4ServerChildrenChannel = AttributeKey.newInstance("clientKey");
        String abk4ServerChildrenChannelValue =  "sameClientValue";

        ChannelFuture channelFuture = serverBootstrap
                .group(boss, worker)
                .channel(NioServerSocketChannel.class)
                //TCP三次握手链接成功队列
                .option(ChannelOption.SO_BACKLOG, 2048)
                //禁用Nagle算法，数据立马发送出去，不需要等待将多个较小的包组合成较大的包进行发送
                .childOption(ChannelOption.TCP_NODELAY, true)
                //全部客户端accept之后，链接的channel都是分配一样的:key-value【全局设置】
                .childAttr(abk4ServerChildrenChannel, abk4ServerChildrenChannelValue)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @SuppressWarnings("deprecation")
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                if (ctx.hasAttr(abk4ServerChildrenChannel)) {
                                    System.out.println(ctx.attr(abk4ServerChildrenChannel).get());
                                }
                                System.out.println(msg);
                            }
                        });
                    }
                })
                .bind(8888).sync();
        boolean success = channelFuture.isSuccess();
        System.out.println("服务绑定状态："+ success);
    }
}

